import * as echarts from '../../ec-canvas/echarts';

Component({
  properties: {
    chartData: {
      type: Object,
      value: { xAxis: [], yAxis: [], series: [] },
    },
    chartOptions: { type: Object, value: {} },
    chartWidth: { type: Number, value: 0 },
    chartHeight: { type: Number, value: 0 },
  },
  data: {
    // 命名为 ecAll，与另一个组件的 ec 完全隔离
    ecAll: {
      lazyLoad: true, // 必须开启延迟加载，确保实例隔离
      onInit: (canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, {
          width, height, devicePixelRatio: dpr
        });
        canvas.setChart(chart);
        return chart;
      }
    }
  },
  lifetimes: {
    ready() { // 替换 attached，确保布局完成后初始化
      this.initChart();
    }
  },
  methods: {
    async initChart() {
      const ecComponent = this.selectComponent('#echartsLine'); // 确保 id 与 wxml 一致
      if (!ecComponent) {
        console.error('echarts-all：未找到 ec-canvas 实例');
        return;
      }
      await ecComponent.init(async (canvas, width, height, dpr) => {
        const myChart = echarts.init(canvas, null, {
          width: this.properties.chartWidth || width,
          height: this.properties.chartHeight || height,
          devicePixelRatio: dpr
        });
        console.log(this.properties, 'this.properties')
        const options = {
          grid: { top: '30', left: '5%', bottom: '50', containLabel: true },
          xAxis: {
            type: this.properties.chartData.category === 'y' ? 'value' : 'category',
            name: this.properties.chartData.xAxisName,
            nameTextStyle: { verticalAlign: 'left', lineHeight: 60, padding: [0, 0, 0, -80] },
            axisLine: { show: true },
            axisLabel: { interval: 0, rotate: 30 },
            data: this.properties.chartData.xAxis || []
          },
          yAxis: {
            name: this.properties.chartData.yAxisName,
            type: this.properties.chartData.category === 'y' ? 'category' : 'value',
            nameTextStyle: { verticalAlign: 'top', padding: [0, 30, 0, 0] },
            axisLine: { show: true },
            data: this.properties.chartData.yAxis || []
          },
          series: this.properties.chartData.series,
          //  || [{
          //   data: this.data.chartData.data || [],
          //   type: this.data.chartData.type,
          //   smooth: true,
          //   label: { show: true, position: 'top' },
          // }],
          ...this.data.chartOptions
        };
        myChart.setOption(options);
        wx.onWindowResize(() => myChart.resize());
        return myChart;
      });
    },
    updateChartData(newData) {
      const ecComponent = this.selectComponent('#echartsLine');
      if (ecComponent && ecComponent.chart) {
        ecComponent.chart.setOption({
          xAxis: { data: newData.xAxis || [] },
          series: [{ data: newData.data || [] }]
        });
      }
    }
  }
});